package com.emip.servlet.authority;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.emip.bean.MenuDefBean;
import com.emip.bean.RoleBean;
import com.emip.config.SysParams;
import com.emip.pojo.Table;
import com.emip.service.MenuDefService;
import com.emip.service.RoleService;
import com.emip.util.TableFormat;

/**
 * 
 * @author Will
 *  角色管理
 */

@Controller
@RequestMapping(value="/authority/roles")
public class RolesAction {

	@Autowired
	RoleService roleService;
	@Autowired
	MenuDefService menuDefService;

	
	@RequestMapping(value="/getAllRolesObj")
	public @ResponseBody List<RoleBean> getAllRolesObj() {
		return roleService.getAll();
	}
	
	@RequestMapping(value="/management")
	public String index() {		
		return "/authorityFunc/RolesManagement";
	}
	
	@RequestMapping(value="/getAllRoles")
	public @ResponseBody Table<RoleBean> getAllRoles() {
		List<RoleBean> result = roleService.getAll();
		int records = result.size();
		int totalPages = records / SysParams.gridDefinedRowNumber + 1;
		return new TableFormat<RoleBean>().formTable(totalPages, 1, records, result);
	}
	
	@RequestMapping(value="/getRoleByID")
	public @ResponseBody RoleBean getRoleByID(
			@RequestParam("eid") int eid) {
		return roleService.getRoleByID(eid);
	}
	
	@RequestMapping(value="/addRole")
	public @ResponseBody RoleBean addRole(
			@RequestParam("eName") String name, 
			@RequestParam("eDescription") String description) {
		return roleService.addRole(name, description);
	}
	
	@RequestMapping(value="/updateRole")
	public @ResponseBody RoleBean updateRole(
			@RequestParam("eID") int id, 
			@RequestParam("eName") String name, 
			@RequestParam("eDescription") String description) {
		return roleService.updateRole(id, name, description);
	}
	
	@RequestMapping(value="/deleteRole")
	public @ResponseBody String deleteRole(@RequestParam("eID") int id) {
		//会将菜单关联一并删除t_role_menu
		roleService.deleteRole(id);
		return "success";
	}
	
	@RequestMapping(value="/getRoleMenus")
	public @ResponseBody List<MenuDefBean> getRoleMenus(
			@RequestParam("eID") int roleID) {
		return menuDefService.getMenuListByRole(roleID);
	}
	
	@RequestMapping(value="/setRoleMenus")
	public @ResponseBody String setRoleMenus(
			@RequestParam("roleID") int roleID, 
			@RequestParam("menuIDs") String menuIDs) {
		//setRoleMenus已经考虑到首先删除该roleID所绑定的menu
		menuIDs = menuIDs.substring(0, menuIDs.length()-1);
		String[] mIDs = menuIDs.split(",");
		roleService.setRoleMenus(roleID, mIDs);
		return "success";
	}
}
